﻿<template>
    <el-dialog
        title="调价"
        v-model="visible"
        :width="1100"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="物料编码">{{entityObj.materialCode}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="物料名称">{{entityObj.materialName}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="类别">{{entityObj.materialTypeName}}</el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="物料规格">{{entityObj.materialSpecs}}</el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="单位">{{entityObj.unitName}}</el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                    <el-form-item label-width="120px" label="价格">{{entityObj.price}}</el-form-item>
                </el-col>-->
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="调价备注">
                        <el-collapse  style="width: 100%;">
                            <div class="collapse-container">
                                <div class="collapse-header" @click="toggleCollapse">
                                    <span></span>
                                    <div style="display: flex;align-items: center;">
                                        <span class="expand-text">{{ isCollapsed ? '展开' : '收起' }}</span>
                                        <img
                                            v-if="isCollapsed"
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-bt.png"
                                        />
                                        <img
                                            v-else
                                            class="icon-img"
                                            src="https://oss.jtmckj.com/pc/images/pay/arrow-top.png"
                                        />
                                    </div>
                                </div>
                            </div>
                            <div v-show="!isCollapsed" class="collapse-content1">
                                <sc-editor
                                    ref="scNotes"
                                    v-model="entityObj.notes"
                                    :height="300"
                                    style="width: 100%;"
                                ></sc-editor>
                            </div>
                        </el-collapse>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="110px" label="供应商">
                        <el-button size="small" @click="addSupplier()">新增供应商</el-button>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row
                v-for="(item,index) in entityObj.innerProtocolRelations"
                :key="index"
                style="margin-top: 10px;"
            >
                <el-col :span="24">
                    <el-form-item label-width="110px">
                        <el-table :data="[item]" border style="width: 100%" default-expand-all>
                            <el-table-column type="expand">
                                <template #default="props">
                                    <div style="padding: 5px 40px;">
                                        <!-- <el-button size="small" @click="addPrice(props.row)">新增价格</el-button> -->
                                        <el-table
                                            :data="props.row.innerProtocolItemPrices"
                                            :border="childBorder"
                                        >
                                            <el-table-column label="供店价" width="150">
                                                <template #default="scope">
                                                    <el-input-number
                                                        v-model="scope.row.price"
                                                        :class="{'bordered': isCurrentDateInValidityRange(scope.row.validityDates)}"
                                                        style="width: 100%"
                                                        :precision="2"
                                                        :step="0.00"
                                                        controls-position="right"
                                                    ></el-input-number>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="最低起送量" width="130">
                                                <template #default="scope">
                                                    <el-input-number
                                                        v-model="scope.row.minApplyQty"
                                                        style="width: 100%"
                                                        :precision="0"
                                                        :step="0"
                                                        controls-position="right"
                                                    ></el-input-number>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="采购模式" width="150">
                                                <template #default="scope">
                                                    <el-select
                                                        placeholder="---采购模式---"
                                                        v-model="scope.row.purchaseSaleType"
                                                        style="width: 100%"
                                                    >
                                                    <el-option
                                                        v-for="item in purchaseSaleTypeOptions"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value"
                                                    />
                                                    </el-select>
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="有效期" width="400">
                                                <template #default="scope">
                                                    <el-date-picker
                                                        style="width: 100%"
                                                        v-model="scope.row.validityDates"
                                                        :class="{'bordered': isCurrentDateInValidityRange(scope.row.validityDates)}"
                                                        type="datetimerange"
                                                        value-format="YYYY-MM-DD HH:mm:ss"
                                                        format="YYYY-MM-DD HH:mm:ss"
                                                        range-separator="-"
                                                        unlink-panels="true"
                                                        start-placeholder="开始时间"
                                                        end-placeholder="结束时间"
                                                        :clearable="false"
                                                        :default-time="defaultTime"
                                                        @change="(dateRange) => changeValidityDates(dateRange, scope.$index)"
                                                    />
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="操作" min-width="80">
                                                <template #default="scope">
                                                    <el-button
                                                        size="small"
                                                        v-if="scope.$index<props.row.innerProtocolItemPrices.length-1"
                                                        @click="deleteRow(props.row,scope.$index, scope.row)"
                                                    >移除</el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="采购价格" width="120" prop="price">
                                <template #default="scope">
                                    <div
                                        :class="{'bordered': scope.row.isValid}"
                                    >{{ scope.row.price }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="供应商编码" width="100" prop="orgCode"></el-table-column>
                            <el-table-column label="供应商" prop="orgName"></el-table-column>
                            <el-table-column label="操作" min-width="200">
                                <template #default="scope">
                                    <el-button
                                        color="#626aef"
                                        icon="Top"
                                        v-if="index>0"
                                        round
                                        style="width: 25px;height: 25px;"
                                        @click="onUp(index,scope.row)"
                                    ></el-button>
                                    <el-button
                                        color="#626aef"
                                        icon="Bottom"
                                        v-if="index< entityObj.innerProtocolRelations.length-1"
                                        round
                                        @click="onDown(index,scope.row)"
                                        style="width: 25px;height: 25px;"
                                    ></el-button>
                                    <el-button
                                        type="danger"
                                        icon="Close"
                                        round
                                        @click="deletePurchaseProtocolItemsRow(index, scope.row)"
                                        style="width: 25px;height: 25px;"
                                    ></el-button>
                                    <el-button
                                        type="primary"
                                        icon="Plus"
                                        round
                                        @click="addPrice(scope.row)"
                                        style="width: 25px;height: 25px;"
                                    ></el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >保 存</el-button>
        </template>
    </el-dialog>
    <template>
        <full-screen-dialog
            v-model="dialogSupplierPrice"
            title="选择供应商"
            :width="800"
            :center="true"
            append-to-body
        >
            <el-row>
                <el-table
                    :data="purchaseProtocolItems"
                    border
                    style="width: 100%"
                    @selection-change="selectionChange"
                >
                    <el-table-column type="selection" width="50"></el-table-column>
                    <el-table-column label="采购价格" width="100" prop="price"></el-table-column>
                    <el-table-column label="供应商编码" width="100" prop="supplierCode"></el-table-column>
                    <el-table-column label="供应商" prop="supplierName"></el-table-column>
                </el-table>
            </el-row>
            <template #footer>
                <el-button @click="materialState = false">取 消</el-button>
                <el-button
                    type="primary"
                    :loading="isSaveing"
                    @click="setPurchaseProtocolItemsChoice"
                >确定</el-button>
            </template>
        </full-screen-dialog>
    </template>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    components: {},
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {},
            supplierState: false,
            applyOrderState: false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {},
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseUnity: [],
            itemsData: [],
            minDate: "",
            maxDate: "",
            dialogSupplierPrice: false,
            purchaseProtocolItems: [],
            selectionRows: [],
            defaultTime: [
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ],
            purchaseSaleTypeOptions:[],
            activeNames: [],
            isCollapsed: true, // 初始状态为收起
        };
    },
    computed: {},
    methods: {
        // 判断当前日期是否在 validityDates 范围内
        isCurrentDateInValidityRange(data) {
            console.log(data);
            if (!Array.isArray(data) || data.length !== 2) {
                // 如果 data 不是数组，或长度不为 2，返回 false
                return false;
            }
            const currentDate = new Date(); // 获取当前日期时间
            const [startDate, endDate] = data;

            if (startDate && endDate) {
                // 将 startDate 和 endDate 转换为 Date 对象
                const start = new Date(startDate);
                const end = new Date(endDate);

                // 判断当前日期是否在有效日期范围内
                return currentDate >= start && currentDate <= end;
                // return true
            }
            return false; // 如果没有有效日期范围
        },
        //显示=
        async open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        disabledDate(time) {
            return (
                time.getTime() <= new Date(this.minDate).getTime() ||
                time.getTime() >= new Date(this.maxDate).getTime()
            );
        },
        //表单提交方法
        submit() {
            if (
                !this.entityObj.innerProtocolRelations ||
                this.entityObj.innerProtocolRelations.length == 0
            ) {
                this.$message.error("供应商不能为空");
                return false;
            }

            if (
                this.entityObj.innerProtocolRelations.some(
                    (p) =>
                        !p.innerProtocolItemPrices ||
                        p.innerProtocolItemPrices.length == 0
                )
            ) {
                this.$message.error("供应商价格不能为空");
                return false;
            }

            if (
                this.entityObj.innerProtocolRelations.some((p) =>
                    p.innerProtocolItemPrices.some(
                        (t) => !t.validityDates[0]
                    )
                )
            ) {
                this.$message.error("请选择时间");
                return false;
            }

            //附属品价格可以为0
            if (
                this.entityObj.innerProtocolRelations.some((p) =>
                    p.innerProtocolItemPrices.some((t) => t.price < 0)
                )
            ) {
                this.$message.error("价格不能小于0");
                return false;
            }

            var exists = this.entityObj.innerProtocolRelations.some((z) =>
                z.innerProtocolItemPrices.some((p) => {
                    return z.innerProtocolItemPrices.some((t) => {
                        if (p !== t) {
                            // 避免与自身比较
                            if (
                                p.validityDates[0] <= t.validityDates[1] &&
                                p.validityDates[1] >= t.validityDates[0]
                            ) {
                                return true;
                            }
                        }
                        return false;
                    });
                })
            );

            if (exists) {
                this.$message.error("不能存在相同时间段的调价记录");
                return false;
            }
            console.log("保存调价记录", this.entityObj);
            this.$emit("setPrice", this.entityObj);
            this.visible = false;
        },
        //表单注入数据
        async setData(data) {
            console.log("data", data);
            this.entityObj = structuredClone(data);
            // this.minDate = this.entityObj.startDate;
            // this.maxDate = this.entityObj.endDate;
            // if(this.entityObj.innerProtocolItemPrices.length>0){
            //     this.minDate = this.entityObj.innerProtocolItemPrices[0].validityDates[0];
            // }
        },
        changeValidityDate(val, index) {
            this.entityObj.innerProtocolItemPrices[
                index + 1
            ].validityDates[1] = tool.getPreviousDayEndTime(val);
            this.minDate = tool.formatDate(val);
            this.entityObj.innerProtocolItemPrices[index].validityDates[0] =
                tool.formatDate(val);
            this.entityObj.innerProtocolItemPrices[index].validityDates[1] =
                this.maxDate;
        },
        changeValidityDates(val, index) {
            // this.entityObj.innerProtocolItemPrices[
            //     index - 1
            // ].validityDates[0] = tool.getPreviousDayEndTime(val[1]);
            // this.entityObj.innerProtocolItemPrices[
            //     index + 1
            // ].validityDates[1] = tool.getPreviousDayEndTime(val[0]);
        },
        deleteRow(row, index) {
            // this.entityObj.innerProtocolItemPrices[index+1].validityDates[1]=this.entityObj.innerProtocolItemPrices[index].validityDates[1];
            row.innerProtocolItemPrices.splice(index, 1);
        },
        addPrice(row) {
            // if (
            //     !this.entityObj.innerProtocolItemPrices[0].validityDates[0]
            // ) {
            //     this.$message.error("请选择时间");
            //     return false;
            // }

            if (
                !row.innerProtocolItemPrices ||
                row.innerProtocolItemPrices.length == 0
            ) {
                row.innerProtocolItemPrices = [
                    { 
                        price: "",
                        minApplyQty:1,
                        purchaseSaleType:0,
                        validityDates: [
                            this.entityObj.startDate,
                            this.entityObj.endDate,
                        ],
                        validityDate: "",
                    },
                ];
                return;
            }

            row.innerProtocolItemPrices.unshift({
                price: "",
                minApplyQty:1,
                purchaseSaleType:0,
                validityDates: [],
                validityDate: "",
            });
        },
        addSupplier() {
            this.dialogSupplierPrice = true;
            console.log("this.entityObj", this.entityObj);
            this.$nextTick(() => {
                this.getMaterialSupplier();
            });
        },
        //获取物料供应商
        async getMaterialSupplier() {
            var materialItemIds = [this.entityObj.materialItemId];
            var purchaseUnityId = this.entityObj.purchaseUnityId;
            var purchaseProtocolItemIds =
                this.entityObj.innerProtocolRelations?.map(
                    (p) => p.purchaseProtocolItemId
                );
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "purchase-protocol/material-protocol-pages",
                    {
                        MaterialItemIds: materialItemIds,
                        PurchaseUnityId: purchaseUnityId,
                        NotProtocolItemIds: purchaseProtocolItemIds,
                    }
                );
                if (returnValue.status == 200) {
                    this.purchaseProtocolItems = returnValue.response.data;
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //移除物料供应商行
        deletePurchaseProtocolItemsRow(index) {
            this.entityObj.innerProtocolRelations.splice(index, 1);
        },
        //选择物料采购明细
        setPurchaseProtocolItemsChoice() {
            console.log("物料供应商选择", this.selectionRows);
            //this.entityObj.innerProtocolRelations = this.selectionRows;
            if (
                !this.entityObj.innerProtocolRelations ||
                this.entityObj.innerProtocolRelations.length == 0
            ) {
                this.entityObj.innerProtocolRelations = [];
            }
            this.selectionRows.map((p) => {
                p.bindOrgType=3;
                p.bindProtocolType=1;
                p.bindProtocolItemId=p.purchaseProtocolItemId;
                p.bindOrgId=p.supplierId;
                p.orgCode=p.supplierCode;
                p.orgName=p.supplierName;
                p.innerProtocolItemPrices = [
                    {
                        price: "",
                        minApplyQty:1,
                        purchaseSaleType:0,
                        validityDates: [],
                        validityDate: "",
                    },
                ];
                this.entityObj.innerProtocolRelations.push(p);
            });

            this.dialogSupplierPrice = false;
            //this.sortFun();
        },
        onUp(index, row) {
            let newArr = this.swapItems(
                this.entityObj.innerProtocolRelations,
                index,
                index - 1
            );
            this.entityObj.innerProtocolRelations = newArr;
        },
        onDown(index, row) {
            let newArr = this.swapItems(
                this.entityObj.innerProtocolRelations,
                index,
                index + 1
            );
            this.entityObj.innerProtocolRelations = newArr;
        },
        sortFun() {
            var arr = this.entityObj.innerProtocolRelations;
            for (let index = 0; index < arr.length; index++) {
                const element = arr[index];
                element.sortNum = index + 1;
            }
        },
        swapItems(arr, index1, index2) {
            arr[index1] = arr.splice(index2, 1, arr[index1])[0];

            for (let index = 0; index < arr.length; index++) {
                const element = arr[index];
                element.sortNum = index + 1;
            }
            return arr;
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    {Codes: ["PurchaseSaleType",]}
                );
                if (returnValue.status == 200) {
                    this.purchaseSaleTypeOptions = returnValue.response.find(
                        (p) => p.code == "PurchaseSaleType"
                    ).optionsDetails;
                    this.purchaseSaleTypeOptions= this.purchaseSaleTypeOptions.filter(p=>p.value<20)
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        toggleCollapse() {
            this.isCollapsed = !this.isCollapsed; // 切换展开/收起状态
        },
    },
    async mounted() {
        this.initOptions();
    },
};
</script>

<style>
.bordered {
    border: 1px solid green;
}
.collapse-container {

   
}

.collapse-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
    padding: 5px;
    padding-left: 0;
    font-weight: bold;
    font-size: 12px;
}
.collapse-content1 {
    padding: 10px;
    background: #f2f2f2;
}
.icon-img {
    width: 16px;
    height: 10px;
    margin-left: 5px;
}
</style>
